package com.zmn.oms.admin.controller.work.modify;

import com.alibaba.fastjson.JSON;
import com.zmn.comment.common.dio.sc.spot.check.photo.ScSpotCheckPhotoAuditDIO;
import com.zmn.comment.common.dro.sc.spot.check.photo.ScSpotCheckPhotoDRO;
import com.zmn.comment.dubbo.interfaces.sc.spot.check.photo.ScSpotCheckPhotoListRemoteService;
import com.zmn.comment.dubbo.interfaces.sc.spot.check.photo.ScSpotCheckPhotoModifyRemoteService;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.business.interfaces.attachment.AttachmentBService;
import com.zmn.oms.business.interfaces.masterphoto.OrderPhotoBService;
import com.zmn.oms.common.annotation.PageRequestCas;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.model.dto.work.modify.OrderPhotoDTO;
import com.zmn.oms.model.entity.conf.attachment.ConfOrderAttachmentCategory;
import com.zmn.oms.model.entity.orderattachment.OrderAttachment;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.attachment.AttachmentDetailGroupVO;
import com.zmn.oms.model.vo.work.OperatePermissionVO;
import com.zmn.oms.model.vo.work.ZsOrderPhotoVO;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.orderattachment.OrderAttachmentService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述：工单照片
 *
 * @author lujia
 * @date 2018/11/07 16:32
 */
@Controller
@Slf4j
@RequestMapping("/work/modify")
public class WorkPhotoController extends OmsBaseController {

    @Autowired
    ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;
    @Autowired
    private OrderPhotoBService orderPhotoBService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderExtendService orderExtendService;
    @Autowired
    OrderAttachmentService orderAttachmentService;
    @Resource
    private AttachmentBService attachmentBService;
    @Reference(version = com.zmn.comment.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private ScSpotCheckPhotoListRemoteService scSpotCheckPhotoListRemoteService;
    @Reference(version = com.zmn.comment.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private ScSpotCheckPhotoModifyRemoteService scSpotCheckPhotoModifyRemoteService;

    /**
     * 工单照片
     */
    @RequestMapping(value = "/orderPhoto")
    @PageRequestCas(type = OrderConsts.ORDER_OP_TYPE_ORDER_PHOTO)
    public ModelAndView findOrderPhoto(Long orderId, Long workId) {

        ModelAndView mv = new ModelAndView("work/modify/orderphoto");
        // 运营后台工单详情
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        ZsOrderPhotoVO zsOrderPhotoVO = new ZsOrderPhotoVO();

        // 微笑行动照片
        try {
            ScSpotCheckPhotoDRO scSpotCheckPhotoDRO = scSpotCheckPhotoListRemoteService.getScSpotCheckPhotoByOrderId(orderId).getData();
            log.info("调用获得微笑行动照片得到的对象:{}", scSpotCheckPhotoDRO);
            if (scSpotCheckPhotoDRO != null) {
                zsOrderPhotoVO.setSmileSscpId(scSpotCheckPhotoDRO.getSscpId());
                zsOrderPhotoVO.setSmileActionSrc(scSpotCheckPhotoDRO.getPhotoUrl());
                zsOrderPhotoVO.setSmileAuditStatus(scSpotCheckPhotoDRO.getAuditStatus());
            }
        } catch (Exception e) {
            log.info("获取微笑行动照片接口异常：{}", e.getMessage());
        }

        // 附件照片
        List<AttachmentDetailGroupVO> attachmentDetailGroupVOList = attachmentBService.getOrderAttachmentByOrderWork(orderWork);
        zsOrderPhotoVO.setAttachmentDetailGroupVOList(attachmentDetailGroupVOList);

        log.info("附件照片：{}", JSON.toJSON(attachmentDetailGroupVOList));

        // 若上月派单工单，下月5号往后也不可标示
        Date distributeTime = orderWork.getDistributeTime();
        boolean supportOperate = DateUtil.isCurMonthOrBetween1to5Day(distributeTime);
        zsOrderPhotoVO.setIsOperate(supportOperate);
        mv.addObject("zsOrderPhotoVO", zsOrderPhotoVO);
        mv.addObject("orderId", orderId);
        mv.addObject("workId", workId);
        return mv;
    }

    /**
     * 保存工单照片
     */
    @ResponseBody
    @RequestMapping(value = "/save/orderPhoto", method = RequestMethod.POST)
    public ResultDTO savePhoto(@RequestBody OrderPhotoDTO orderPhotoDTO) {
        log.info("保存工单照片入参:{}", orderPhotoDTO);
        try {
            OperatePermissionVO operatePermission = orderWorkOperatePermissionBService.getOperatePermission(orderPhotoDTO.getOrderId(), orderPhotoDTO.getWorkId(), OrderConsts.ORDER_OP_TYPE_ORDER_PHOTO);
            if (!operatePermission.getCanOperate()) {
                return ResultDTO.fail(operatePermission.getMsg());
            }

            // 查询旧附件数据（为了在工单日志中对比是否审批过照片）
            List<OrderAttachment> dbAttachmentList = orderAttachmentService.listAttachmentByOrderId(orderPhotoDTO.getOrderId());
            orderPhotoDTO.setOldAttachmentList(dbAttachmentList);

            List<OrderAttachment> attachmentList = orderPhotoDTO.getAttachmentList();
            if (CollectionUtils.isNotEmpty(attachmentList)) {

                List<OrderAttachment> collect = attachmentList.stream().filter(item -> Objects.nonNull(item.getReviewStatus())).collect(Collectors.toList());
                // 更新类型
                if (CollectionUtils.isNotEmpty(dbAttachmentList)) {
                    Map<Long, Integer> attachmentMap = dbAttachmentList.stream().
                            collect(Collectors.toMap(item -> item.getAttachmentId(), item -> item.getType(), (p, u) -> p));
                    collect.forEach(item -> {
                        Integer type = attachmentMap.get(item.getAttachmentId());
                        if (type != null) {
                            item.setType(type);
                        }
                    });
                }
                
                orderPhotoDTO.setAttachmentList(collect);
                orderPhotoBService.updateOrderPhoto(orderPhotoDTO);
            }


            try {
                // 微笑行动审核
                ScSpotCheckPhotoAuditDIO scSpotCheckPhotoAuditDIO = new ScSpotCheckPhotoAuditDIO();
                scSpotCheckPhotoAuditDIO.setSscpId(orderPhotoDTO.getSmileSscpId());
                scSpotCheckPhotoAuditDIO.setAuditStatus(orderPhotoDTO.getSmileAuditStatus());
                if (scSpotCheckPhotoAuditDIO.getSscpId() != null && scSpotCheckPhotoAuditDIO.getAuditStatus() != null) {
                    scSpotCheckPhotoAuditDIO.setAuditerId(orderPhotoDTO.getOperatorId());
                    scSpotCheckPhotoAuditDIO.setAuditer(orderPhotoDTO.getOperator());
                    scSpotCheckPhotoAuditDIO.setAuditerType(orderPhotoDTO.getOperatorType());
                    scSpotCheckPhotoModifyRemoteService.modifyScSpotCheckPhotoAuditStatusBySscpId(scSpotCheckPhotoAuditDIO);
                }
            } catch (Exception ex) {
                log.info("{}微笑行动照片审核失败：{}", orderPhotoDTO.getSmileSscpId(), ex);
            }

            return ResultDTO.success();
        } catch (Exception e) {
            return ResultDTO.fail(e.getMessage());
        }
    }

    @RequestMapping(value = "/uploader/orderPhoto")
    @ResponseBody
    public ResultDTO uploaderImage(MultipartFile file) {
        return super.uploaderImage(file, "/oms/order/photo");
    }

}